import { Sequelize, DataTypes, Model, Optional } from "sequelize";
import { User } from "../interfaces/user.interface";
export type UserCreationAttributes = Optional<User, "id">;
/**
 * @description 用户模型模块
 * 
 * 该模块定义了用户数据模型，用于:
 * 1. 与数据库users表进行映射
 * 2. 提供用户数据的类型定义和验证
 * 3. 实现用户相关的数据操作接口
 */

export class UserModel
	extends Model<User, UserCreationAttributes>
	implements User
{
	public id: number;
	public username: string;
	public password: string;
	public ruleId: number;
	public readonly createdAt!: Date;
	public readonly updatedAt!: Date;
	public readonly deletedAt!: Date;
}


/**
 * @description 用户模型类
 * @extends Model
 * @implements User
 * 
 * @property {number} id - 用户ID，自增主键
 * @property {string} username - 用户名，唯一
 * @property {string} password - 用户密码
 */

export default function (sequelize: Sequelize): typeof UserModel {
	UserModel.init(
		{
			id: {
                // 设置ID字段为自动递增
                autoIncrement: true,
                type: DataTypes.INTEGER,  // 使用UNSIGNED确保ID为正整数
				primaryKey: true,
				allowNull: false,  // 添加这行
    			field: 'id'  // 明确指定字段名
			},
			
            // 用户名字段
            // 不允许为空，必须唯一
            // 用于用户登录和身份识别
            username: {
				allowNull: false,
				type: DataTypes.STRING,
				unique: true,
			},
			password: {
				allowNull: false,
				type: DataTypes.STRING,
			},
            ruleId: {
				allowNull: true,
				type: DataTypes.STRING,
				unique: true,
			},
			updatedAt: {
				type: DataTypes.DATE,
			},
			createdAt: {
				type: DataTypes.DATE,
			},
			deletedAt: {
				type: DataTypes.DATE,
			},
		},
		{
			tableName: "user",
			sequelize,
			deletedAt: "deletedAt",
			paranoid: false,
		}
	);
	return UserModel;
}
